package javabase.desginpattern.structure.proxy.jdkdynamicProxy;

import javabase.desginpattern.structure.proxy.HelloImpl;
import javabase.desginpattern.structure.proxy.IHello;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author fance
 * @date 18-4-27 下午4:38
 */
public class DynamicProxy implements InvocationHandler {
    private Object target;

    public DynamicProxy(Object target) {
        this.target = target;
    }

    public <T> T getProxy() {
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object res = method.invoke(target, args);
        after();
        return res;
    }

    private void before() {
        System.out.println("before");
    }
    private void after() {
        System.out.println("after");
    }

    public static void main(String[] args) {
        IHello hello = new HelloImpl();

        DynamicProxy dynamicProxy = new DynamicProxy(hello);
        /*IHello helloProxy = (IHello) Proxy.newProxyInstance(hello.getClass().getClassLoader(),
                hello.getClass().getInterfaces(),
                dynamicProxy);*/

        IHello helloProxy = dynamicProxy.getProxy();
        helloProxy.say("fance");
    }
}
